package com.example.exampleofeasyexcel.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import com.example.exampleofeasyexcel.bean.UserVo;
import com.example.exampleofeasyexcel.handler.SpinnerWriteHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author CH
 * @date 2022/8/1
 */
@RestController
public class DemoController {

    /**
     * 从web导出
     *
     * @param response HttpServletResponse
     * @return String
     */
    @GetMapping("/easyWebExport")
    public String easyWebExport(HttpServletResponse response) {
        String fileName = "Web导出文件";
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));

            Short headRowHeight = 20;
            Short contentRowHeight = 15;
            // 此处可自定义输出列
            Set<String> includes = new HashSet<>();
            includes.add("name");
            includes.add("phone");
            includes.add("age");

            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            EasyExcelFactory.write(response.getOutputStream(), UserVo.class)
                    .registerWriteHandler(new SimpleRowHeightStyleStrategy(headRowHeight, contentRowHeight))
                    .autoCloseStream(true)
                    .includeColumnFieldNames(includes)
                    .sheet(fileName)
                    .doWrite(getData());
        } catch (Exception e) {
            return e.getMessage();
        }
        return null;
    }

    /**
     * 导出到本地
     *
     * @return String
     */
    @GetMapping("/localExport")
    public String localExport() throws IOException {
        String fileName = "人员表";
        String exportTask = System.getProperty("user.dir") + File.separator + "exportTask" + File.separator;
        Path path = Paths.get(exportTask);
        if (Files.notExists(path)) {
            Files.createDirectories(path);
            Path pathFile = Paths.get(exportTask, fileName + ".xlsx");
            OutputStream out = Files.newOutputStream(pathFile.toFile().toPath());
            // 下拉框
            Map<Integer, String[]> mapDropDown = new HashMap<>();
            mapDropDown.put(0, new String[]{"选项1", "选项2"});

            EasyExcelFactory.write(out)
                    .registerWriteHandler(new SpinnerWriteHandler(mapDropDown))
                    .autoCloseStream(true)
                    .sheet(fileName)
                    .head(getHead())
                    .doWrite(getList());
            out.close();
        }
        return "成功";
    }

    /**
     * 模拟数据 1
     * 实体类数据
     *
     * @return
     */
    public List<UserVo> getData() {
        List<UserVo> list = new ArrayList<>();
        UserVo v1 = new UserVo();
        v1.setName("A");
        v1.setAge("10D");
        v1.setPhone("132");
        UserVo v2 = new UserVo();
        v2.setName("B");
        v2.setAge("10D");
        v2.setPhone("132");
        return list;
    }

    /**
     * 模拟数据 2
     * 想要导出的数据
     *
     * @return
     */
    public List<Map<Integer, Object>> getList() {
        List<Map<Integer, Object>> list = new ArrayList<>();
        Map<Integer, Object> m1 = new HashMap<>();
        m1.put(0, "年龄1");
        m1.put(1, "姓名1");
        list.add(m1);
        Map<Integer, Object> m2 = new HashMap<>();
        m2.put(0, "年龄2");
        m2.put(1, "姓名2");
        list.add(m2);
        return list;
    }

    /**
     * 想要导出的头
     *
     * @return
     */
    public List<List<String>> getHead() {
        List<List<String>> heads = new ArrayList<>();
        List<String> h1 = new ArrayList<>();
        h1.add("年龄");
        heads.add(h1);
        List<String> h2 = new ArrayList<>();
        h2.add("姓名");
        heads.add(h2);
        return heads;
    }
}
